<template>
  <div>
    <BasicDrawer
      v-bind="$attrs"
      @register="registerDrawer"
      showFooter
      destroyOnClose
      :title="getTitle"
      width="70%"
      @ok="handleSubmit"
    >
      <Spin :spinning="loading">
        <BasicForm @register="registerForm" @field-value-change="handleChangeFeild" />
      </Spin>
    </BasicDrawer>
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { Spin } from 'ant-design-vue';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal';
  import { useTable } from '/@/components/Table';

  import { formSchema, columnsAuth } from './menu.data';
  import { addMenuApi, updateMenuApi, getMenuItemApi } from '/@/api/admin/menu';
  import { deleteModuleAuthApi } from '/@/api/admin/auth';

  export default defineComponent({
    name: 'MenuDrawer',
    components: {
      Spin,
      BasicDrawer,
      BasicForm,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const loading = ref(false);
      const isUpdate = ref(false);
      const isModelAuth = ref(false);
      const isModelBind = ref(false);

      const moduleId = ref();
      let updateInfo = {};

      const actionAuths = ref<any>();
      const { createMessage } = useMessage();

      const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
        labelWidth: 160,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: { lg: 11, md: 23 },
      });

      async function getMenuItem(moduleId) {
        const res = await getMenuItemApi(moduleId);

        const { module, moduleUserTypes, usingHandles } = res;
        actionAuths.value = usingHandles || [];
        return { module, moduleUserTypes, usingHandles };
      }

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();

        loading.value = true;
        setDrawerProps({ confirmLoading: true });
        isUpdate.value = !!data?.isUpdate;
        if (unref(isUpdate)) {
          moduleId.value = data.record.moduleId;
          const { module } = await getMenuItem(moduleId.value);

          updateInfo = module;
          isModelAuth.value = module.modType === 1;
          isModelBind.value = module.modelClassify;
          module.extMeta = JSON.stringify(module.extMeta || '{}');
          let icon = module.icon.split(',').map((i) => {
            return {
              url: i,
            };
          });

          setFieldsValue({ ...module, icon: icon });
        } else {
          let parentId = data.record.id;
          moduleId.value = '';
          setFieldsValue({
            parentId,
          });
        }

        loading.value = false;
        setDrawerProps({ confirmLoading: false });
      });
      // , { setTableData }
      const [registerTable] = useTable({
        columns: columnsAuth,
        pagination: false,
        striped: false,
        bordered: true,
        showIndexColumn: false,
        canResize: false,
        actionColumn: {
          width: 200,
          title: '操作',
          dataIndex: 'action',
          fixed: undefined,
        },
      });

      const [registerModal, { openModal }] = useModal();

      const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));
      function toJson(str) {
        try {
          return JSON.parse(str || '{}');
        } catch (e) {
          return {};
        }
      }
      async function handleSubmit() {
        try {
          loading.value = true;
          const values = await validate();
          if (values.icon) {
            values.icon = values.icon.map((i) => i.url).toString();
          }
          setDrawerProps({ confirmLoading: true });

          const apiFn = unref(isUpdate) ? updateMenuApi : addMenuApi;
          values.menuType = 0;
          values.typeFlag = 0;
          values.modType = 0;
          values.typeFlag = 0;
          if (!unref(isUpdate)) {
            values.typeRight = 1;
            values.modRight = 1;
          }

          const extMeta = toJson(values.extMeta);
          const params = Object.assign(updateInfo, values, { extMeta });

          await apiFn(params);
          createMessage.success('操作成功');
          closeDrawer();
          emit('success');
        } finally {
          loading.value = false;
          setDrawerProps({ confirmLoading: false });
        }
      }

      function handleEdit(record: Recordable) {
        openModal(true, {
          record,
          isUpdate: true,
        });
      }

      async function handleDelete(record: Recordable) {
        console.log('record', record);
        const { moduleId, userFlag } = record;
        await deleteModuleAuthApi(moduleId, userFlag);
        createMessage.success('操作成功');
        getMenuItem(moduleId);
      }

      function addAuthHandle() {
        openModal(true, {
          record: { moduleId: moduleId.value },
          idupdate: false,
        });
      }

      function handleSuccess() {
        getMenuItem(moduleId.value);
      }
      function changeModtype(v) {
        isModelAuth.value = v === 1;
      }
      function handleChangeFeild(key, value) {
        console.log(key, value);
        // if (key === 'icon') {
        //   icon = value.map((i) => i.url).toString();
        // }
        if (key === 'modelClassify') {
          isModelBind.value = !!value;
        }
        if (key === 'modType') {
          changeModtype(value);
        }
      }

      return {
        loading,
        isUpdate,
        getTitle,
        actionAuths,
        moduleId,
        isModelAuth,
        isModelBind,
        registerDrawer,
        registerForm,
        registerTable,
        registerModal,
        handleEdit,
        handleSubmit,
        handleDelete,
        addAuthHandle,
        handleSuccess,
        changeModtype,
        handleChangeFeild,
      };
    },
  });
</script>
